from fastapi import APIRouter, Request, HTTPException
from fastapi.responses import StreamingResponse, JSONResponse
from pydantic import BaseModel

from database.database import engine
from sqlalchemy import text


router = APIRouter(
    prefix='/member',
    tags = ['会员中心']
)

def select_category_head():
    # try:
    with engine.connect() as conn:
        sql = text(f'''
        select * from smart_sales_category where level = 1;
        ''')
        result = conn.execute(sql).fetchall()
    return result
    # except:
    #   pass

def select_category_info(id):
    # try:
    with engine.connect() as conn:
        sql = text(f'''
        select * from smart_sales_category where id = :id;
        ''')
        result = conn.execute(sql, [{'id': id}]).fetchone()
    return result
    # except:
    #   pass

def select_category_children(parent):
    # try:
    with engine.connect() as conn:
        sql = text(f'''
        select id, name, picture, null as children, null as goods from smart_sales_category where parent = :parent;
        ''')
        result = conn.execute(sql, [{'parent': parent}]).fetchall()
    return result
    # except:
    #   pass


@router.get("")
def category_info(id: int):
    result = select_category_info(id)
    if result:
        category_dict = result._asdict()
        category_children = select_category_children(category_dict["id"])
        category_dict["children"] = [child._asdict() for child in category_children]

        data = { "code": 0, "message": "操作成功" }
        data["result"] = category_dict
        return JSONResponse(status_code=200, content=data)
    else:
        data = { "code": 2, "msg": "操作失败" }
        return JSONResponse(status_code=201, content=data)
